package com.it.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/19/22:20
 **/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    // 构建CORS配置
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许所有域名进行跨域请求
        corsConfiguration.addAllowedHeader("*"); // 允许携带任何头信息
        corsConfiguration.addAllowedMethod("*"); // 允许任何请求方法
        corsConfiguration.addExposedHeader("Authorization"); // 允许前端获取自定义的头部信息
        return corsConfiguration;
    }
    
    // 创建CORS过滤器Bean
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
    
    // 配置全局CORS
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
              .allowedOrigins("*") // 允许所有域名进行跨域请求
              .allowedMethods("GET", "POST", "DELETE", "PUT") // 允许的请求方法
              .maxAge(3600); // 预检请求的有效期，单位秒
    }
}
